package zzps.exeed.kernel.tool;

import java.lang.reflect.*;
import java.util.*;

/**
 * 反射工具
 */
public class ReflectTool {

    public static <T> T newInstance(String clazz,ClassLoader classLoader) {
        try {
            return (T) classLoader.loadClass(clazz).getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T newInstance(Class<?> clazz) {
        try {
            return (T) clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static <T> T newInstance(Constructor<?> constructor) {
        try {
            return (T) constructor.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //获取无参构造器
    public static Constructor<?> getConstructor(Class<?> clazz) {
        try {
            return clazz.getDeclaredConstructor();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    //获取无static final等修饰的字段
    public static void getNormalField(Class<?> clazz,Map<String,Field> fieldMap,boolean supers){
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            int modifiers = field.getModifiers();
            if (Modifier.isFinal(modifiers)||Modifier.isStatic(modifiers)){
                continue;
            }
            field.setAccessible(true);
            fieldMap.putIfAbsent(field.getName(),field);
        }
        Class<?> superclass = clazz.getSuperclass();
        if (superclass != Object.class){
            getNormalField(superclass,fieldMap,supers);
        }
    }


    public static void setField(Object object,Object fieldValue,Field field){
        try {
            field.set(object,fieldValue);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
